/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {StyleSheet, Text, Dimensions, View, Image, PixelRatio, Platform, NativeModules, TouchableHighlight, ListView, ScrollView} from 'react-native';

import Common from '../../component/common';

import ToolbarComponent from '../../component/ToolbarComponent';

import Loading from '../../component/loading';

import LoadError from '../../component/loadError';

// import styles from '../../style/media';

import Article from './article';

import stylesm from '../../style/media';

import ScreenUtils from '../../component/ScreenUtils';

const totalWidth = Dimensions.get('window').width;

const wechat = require('../../images/wechat.png');
const weibo = require('../../images/weibo.png');
const web = require('../../images/newspaper.png');

export default class NewsList extends Component {
  constructor(props) {
    super(props);
    var dsNews = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      loading: false,
      loadingSen: false,
      success: false,
      isMore: true,
      newsDataSource: dsNews,
    };
    this.news = [];
    this.newsmore = [];
    this.newstotal = [];
  }
  componentWillMount(){
    // this.news = [1,2,3,4,5,7,8,9];
    // this.setState({
    //     newsDataSource: this.state.newsDataSource.cloneWithRows(this.news),
    //   });
  }
  componentDidMount(){
    this.fetchData();
  }
  fetchData = () => {
    this.setState({
      loading: true,
      success: false,
    });
    let formData = new FormData();
    formData.append("page", 1);
  	Common.fetchData("post", "/billboard/hotarticleList", formData, (responseData) => {
      console.log(responseData);
      this.news = responseData.resultList;
      this.setState({
        loading: false,
        success: true,
        isMore: responseData.resultList.length == 20,
        newsDataSource: this.state.newsDataSource.cloneWithRows(this.news),
      })
    },() => {
      this.setState({loading: false,
                      success: false,
                      errorMessage: "请求失败",
                    });
    },() => {
      this.setState({loading: false,
                      success: false,
                      errorMessage: "请求失败",
                    });
    });
  };
  newsMore = () => {
    this.setState({loadingSen: true});
    this.timer = setTimeout(() => {
      if(!this.newsmore.length){
        let formData = new FormData();
        formData.append("page",2);
        Common.fetchData("post","/billboard/hotarticleList",formData,(responseData) => {
          this.newsmore = responseData.resultList;
          this.newstotal = this.news.concat(this.newsmore);
          this.setState({
            loadingSen: false,
            isMore: false,
            newsDataSource: this.state.newsDataSource.cloneWithRows(this.newstotal)});
        },() => {
          console.log("error");
        }, () => {
          console.log("error link");
        });
      }else{
        this.newstotal = this.news.concat(this.newsmore);
        this.setState({
            loadingSen: false,
            isMore: false,
            newsDataSource: this.state.newsDataSource.cloneWithRows(this.newstotal)});
      }
      clearTimeout(this.timer);
    }, 500);
  };
  newsRestore = () => {
    this.setState({
      isMore: true,
      newsDataSource: this.state.newsDataSource.cloneWithRows(this.news)});
    
  };
  renderListHeader(){
  	return(
  		<View style={styles.topStyle}></View>
  	)
  }
  linking = (val) => {
    if(Platform.OS == 'ios'){
      NativeModules.JsAndroid.openUrl(val.url);
    }else{
      Common.onForward(this, Article, val, 4);
    }
  };
  renderRow = (val) => {
    let sourceImage ;
    switch(val.scrabbleType){
      case 'wechat':
        sourceImage = wechat;
        break;
      case 'web':
        sourceImage = web;
        break;
      default :
        sourceImage = weibo;
        break;
    }
    return (
      <TouchableHighlight 
      	style={styles.newListWrap} 
      	underlayColor="#fafafa" 
      	delayPressIn={100} 
      	onPress={() => {this.linking(val)}}
      >
        <View style={styles.newsListItem}>
          <View style={styles.newsText}>
            <Text style={styles.newsTitle} numberOfLines={2}>{val.frameTitle || val.title}</Text>
            <View style={styles.newsSource}>
            	<View style={styles.newsAout}>
            		<Image style={styles.infoAboutImage} source = {sourceImage}/>
            		<Text style={styles.infoAboutText}>{val.company}</Text>
            	</View>
            	<View style={[styles.newsAout,{marginLeft: 10}]}>
            		<Image style={styles.infoAboutImageTimer} source = {require('../../images/timer.png')}/>
            		<Text style={styles.infoAboutText}>{Common.beforeTime(val.subcribeTime,5)}</Text>
            	</View>
            	{/*<View style={styles.newsAout}>
            		<Text style={styles.infoAboutText}>{val.clickCount || 0}</Text>
            		<Text style={styles.infoAboutText}>阅读</Text>
            	</View>*/}
            </View>
          </View>
          
          {
            val.img?
            <View style={styles.newsPic}>
              <Image style={styles.newsAboutPic} source ={{uri:val.img}}/>
            </View>:null
          }
          {/*
          <View style={[styles.newsPic,{borderColor: '#ededed',borderWidth: 1/PixelRatio.get()}]}>
            <Text style={styles.newsAboutTip}>暂无图片</Text>
          </View>
          */}
        </View>
      </TouchableHighlight>
    )
  };
  render() {
    return (
      <View style={styles.news}>
        <ToolbarComponent
          leftItem={{
            title: 'Back',
            layout: 'icon',
            icon: require("../../images/back.png"),
            onPress: () => {
               Common.onBack(this,{"id":this.props.did,"type":this.props.name,"collectionStatus":this.collection == this.state.isCollection});
            },
          }}
        >
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT} numberOfLines={1}>资讯</Text>
          </View>
        </ToolbarComponent>
        {
          (this.state.loading?
            <Loading />:
            (this.state.success?
              <View style={styles.newsList}>
              	<ScrollView style={styles.bottomStyle}>
      	          {this.news.length?
      	            <ListView
      	              scrollEnabled={true}
      	              removeClippedSubviews={false}
      	              dataSource={this.state.newsDataSource}
      	              renderRow={this.renderRow.bind(this)}
      	              renderHeader ={this.renderListHeader}
      	              enableEmptySections={true}
      	              showsVerticalScrollIndicator ={false}
      	            />:null
      	          }
                  {this.news && this.state.isMore?
                  <TouchableHighlight underlayColor="transparent" style={{backgroundColor: 'white'}} disabled={this.state.loading} onPress={this.newsMore}>
                  {
                    this.state.loadingSen?<View style={stylesm.reportMore} ><Text style={stylesm.reportMoreT}>加载中...</Text></View>:<View style={stylesm.reportMore} ><Image style={stylesm.reportMoreI} source={require('../../images/open.png')} /><Text style={stylesm.reportMoreT}>查看所有文章</Text></View>
                  }
                  </TouchableHighlight>:
                  (
                    !this.state.isMore && this.news.length > 20?
                      <TouchableHighlight underlayColor="transparent" style={{backgroundColor: 'white'}} onPress={this.newsRestore}>
                        <View style={stylesm.reportMore} >
                          <Image style={stylesm.reportMoreI} source={require('../../images/close.png')} />
                          <Text style={stylesm.reportMoreT}>收起</Text>
                        </View>
                      </TouchableHighlight>:null
                  )
                }
                  <View style={styles.bottomStyle}></View>
                </ScrollView>
              </View>
              :
              <LoadError reload={this.fetchData} reason={this.state.errorMessage}/>))
        }
      </View>
    )
  }
}

const styles = StyleSheet.create({
  news: {
    flex: 1,
    backgroundColor: "#f6f6f6",
  },
  toolbarV: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: 20
  },
  topStyle:{
  	marginTop:ScreenUtils.scaleSize(20),
  	borderTopWidth:1/PixelRatio.get(),
  	borderColor:"#ececec",
  },
  newsList:{
  	flex:1,
  	backgroundColor:"#fff",
  },
  newListWrap:{
  	width:totalWidth,
  	paddingVertical:ScreenUtils.scaleSize(24),
  	paddingHorizontal:ScreenUtils.scaleSize(26),
    borderTopWidth:1/PixelRatio.get(),
    flexDirection:"row",
    borderColor:"#d5d5d5",
    backgroundColor:"#fff",
  },
  newsListItem:{
  	flex:1,
    // height:ScreenUtils.scaleSize(128),
    flexDirection:"row",
    justifyContent:'space-between',
  },
  newsText:{
  	flex:1,
  	// height:ScreenUtils.scaleSize(128),
  	
  	flexDirection:"column",
  	justifyContent:'space-between',
  },
  newsPic:{
  	width:ScreenUtils.scaleSize(190),
  	height:ScreenUtils.scaleSize(128),
    marginLeft:ScreenUtils.scaleSize(36),
    justifyContent: 'center',
    alignItems: 'center',
  },
  newsAboutPic:{
  	width:ScreenUtils.scaleSize(190),
  	height:ScreenUtils.scaleSize(128),  	
  },
  newsAboutTip:{
    color: '#ededed',
    fontSize: 12,
  },
  newsTitle:{
  	fontSize:ScreenUtils.scaleSize(28),
  	color:"#000",
  },
  newsSource:{
  	flexDirection:"row",
  	justifyContent:'flex-start',
    marginTop: ScreenUtils.scaleSize(32),
  },
  newsAout:{
  	flexDirection:"row",
  	marginLeft:5,
  	justifyContent:"center",
  	alignItems:"center",
  },
  infoAboutImage:{
  	width:ScreenUtils.scaleSize(22),
  	height:ScreenUtils.scaleSize(18),
  	resizeMode: 'contain',
  },
  infoAboutText:{
  	fontSize:7,
  	color:"#9d9d9d",
  	paddingLeft:3,	
  },
  bottomStyle:{
  	flex:1,
  	height:ScreenUtils.scaleSize(78),
  	backgroundColor: "#f6f6f6",
  }
});